#include "monitor.h"
#include "ui_monitor.h"
#include "global.h"

Monitor::Monitor(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Monitor)
    ,threadMonitor(new QThread(this))
    ,threadMqtt(new QThread(this))
{
    ui->setupUi(this);
    this->setFixedSize(1920,1080);
    this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint
                         | Qt::WindowSystemMenuHint
                         | Qt::WindowMinimizeButtonHint
                         | Qt::WindowMaximizeButtonHint);

    PMonitorWork = new MonitorWork();
    connect(PMonitorWork, &MonitorWork::infoOccurred,
            this, &Monitor::fnMonitorWorkInfo);
    connect(PMonitorWork, &MonitorWork::versionReceived,
            this, &Monitor::fnOpenDeviceDetail);
    connect(PMonitorWork, &MonitorWork::reqSystemVersion,
            this, &Monitor::fnCheckNewVersion);

    PMonitorWork->moveToThread(threadMonitor);
    connect(threadMonitor, &QThread::finished,
            PMonitorWork, &MonitorWork::deleteLater);
    threadMonitor->start();
    this->fnInitFormSlots();
}

Monitor::~Monitor()
{
    threadMonitor->quit();
    if (!threadMonitor->wait(1000)) {
        threadMonitor->terminate();    // 强制终止
        threadMonitor->wait();
    }
    delete threadMonitor;

    threadMqtt->quit();
    if (!threadMqtt->wait(1000)) {
        threadMqtt->terminate();    // 强制终止
        threadMqtt->wait();
    }
    delete threadMqtt;

    if (Global::NetworkManager) {
        delete Global::NetworkManager;
        Global::NetworkManager = nullptr;
    }
    delete ui;
}

void Monitor::fnInitFormSlots(){
    // qDebug() << "Monitor" << __LINE__ << QThread::currentThreadId();
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Monitor::fnUpdateTime);
    timer->start(1000);
    ui->GridLayoutCurrDatetime->addWidget(ui->labCurrTime, 0,0,2,1);

    // 异步加载字体
    QtConcurrent::run([=](){
        int fontId = QFontDatabase::addApplicationFont(":/images/BebasNeue-Regular.ttf");
        if (fontId != -1) {
            QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
            if (!fontFamilies.isEmpty()) {
                // 切换到UI线程设置字体
                QMetaObject::invokeMethod(this, [=](){
                        QFont font(fontFamilies.at(0));
                        ui->labCurrTime->setFont(font);
                    }, Qt::QueuedConnection);
            }
        }
    });

    ui->labCurrTime->setStyleSheet("font-size:40pt;");

    ui->labCompany->setText(Global::CompanyName);
    ui->labVersion->setText(QString("v%1").arg(APP_VERSION));
    ui->labPlatformName->setText(Global::PlatformName);

    //字体图标
    int IcoFontId = QFontDatabase::addApplicationFont(":/images/icofont.ttf");
    QString IcoFontName = QFontDatabase::applicationFontFamilies(IcoFontId).at(0);
    Global::IconFont = QFont(IcoFontName);

    //设置按钮
    ui->BtnNavigation->setFont(Global::IconFont);
    ui->BtnNavigation->setText(QChar(0xf006));
    connect(ui->BtnNavigation, &QPushButton::clicked, this, &Monitor::onOpenNavigation);

    //最小化最大化按钮
    ui->BtnMainMin->setFont(Global::IconFont);
    ui->BtnMainMin->setText(QChar(0xef9a));
    connect(ui->BtnMainMin, &QPushButton::clicked, this, &Monitor::onWindowGeometry);

    ui->BtnMainMax->setFont(Global::IconFont);
    ui->BtnMainMax->setText(QChar(0xef52));
    connect(ui->BtnMainMax, &QPushButton::clicked, this, &Monitor::onWindowGeometry);

    ui->BtnMainClose->setFont(Global::IconFont);
    ui->BtnMainClose->setText(QChar(0xeee4));
    connect(ui->BtnMainClose, &QPushButton::clicked, this, &Monitor::onWindowGeometry);

    //初始化配置
    Global::fnInitializationConfig();
    connect(MGlobal::fnGetInstance(), &MGlobal::CallInsidePageAction, this, &Monitor::fnInsidePageAction);

    // 检查新版本升级 // 用户登录
    QTimer::singleShot(0, this, [=](){
        QMetaObject::invokeMethod(PMonitorWork, "fnCheckNewVersion",
                                  Qt::QueuedConnection,
                                  Q_ARG(bool, true));
        // 版本检查结束后执行登录检查
        // fnShowLoginWidget();
    });
}

/**
 * 用户退出登录/登录成功
 * @brief Monitor::fnLoginSucceeded
 */
void Monitor::fnLoginSucceeded(){
    if(Global::usrLoggedInfo.isEmpty()){
        fnShowLoginWidget();
        return;
    }
    //执行登录成功之后的操作
    if(PGUsrLogin){
        PGUsrLogin->deleteLater();
        PGUsrLogin = nullptr;
    }

    // 设置平台名称
    this->fnInsidePageAction(QStringList("PlatformNameChanged"));

    // MQTT
    PQtMqtt = new QtMqtt();
    PQtMqtt->moveToThread(threadMqtt);
    connect(threadMqtt, &QThread::started,
            PQtMqtt, &QtMqtt::fnMqttConnectStart);
    connect(threadMqtt, &QThread::finished,
            PQtMqtt, &QtMqtt::fnMqttClosed);
    connect(threadMqtt, &QThread::finished,
            threadMqtt, &QThread::deleteLater);
    threadMqtt->start();

    // 加载其它模块
    QMetaObject::invokeMethod(this, "fnChainLoading",
        Qt::QueuedConnection,
        Q_ARG(int, 1));
}

void Monitor::fnChainLoading(int index){
    switch (index) {
    case 1:
        // 加载设备列表
        if (PDevicesList)
            ui->frmDevicesList->removeWidget(PDevicesList);
        PDevicesList = new DevicesList(this);
        ui->frmDevicesList->addWidget(PDevicesList);
        ui->frmDevicesList->setCurrentWidget(PDevicesList);
        break;
    case 2:
        // 加载头部统计
        PTopStatistics = new TopStatistics(this);
        ui->frmStatistics->addWidget(PTopStatistics);
        ui->frmStatistics->setCurrentWidget(PTopStatistics);
        break;
    case 3:
        // 加载地图
        PFormMap = new FormMap(this);
        ui->frmMap->addWidget(PFormMap);
        ui->frmMap->setCurrentWidget(PFormMap);
        break;
    case 4:
        // 加载年发电量统计
        PFDLiangStat = new FDLiangStat(this);
        ui->frmElectricity->addWidget(PFDLiangStat);
        ui->frmElectricity->setCurrentWidget(PFDLiangStat);
        break;
    case 5:
        // 加载设备消息
        PDeviceNews = new DeviceNews(this);
        ui->frmDevnews->addWidget(PDeviceNews);
        ui->frmDevnews->setCurrentWidget(PDeviceNews);
        break;
    case 6:
        // 加载设备统计（图表）
        PDeviceStatistics = new DeviceStatistics(this);
        ui->frmChartstatistics->addWidget(PDeviceStatistics);
        ui->frmChartstatistics->setCurrentWidget(PDeviceStatistics);
        ui->frmChartstatistics->setFixedWidth(380);
        connect(PDeviceStatistics, &DeviceStatistics::CallStatCompleted, this, &Monitor::fnShowFaultAlarm);
        break;
    case 7:
        // 设备轮播
        PDevCarousel = new DevCarousel(this);
        ui->frmCarousel->addWidget(PDevCarousel);
        ui->frmCarousel->setCurrentWidget(PDevCarousel);

        // 打开摄像头监控窗口
        connect(PDevCarousel, &DevCarousel::reqOpenPreviewCamera, this, [=](){
            if(PCameraMonitor == nullptr){
                PCameraMonitor = new CameraMonitor(this);
                connect(PCameraMonitor, &CameraMonitor::restartStreaming,
                        PDevCarousel, &DevCarousel::reqStartStreaming);
            }
            if(PCameraMonitor && !PCameraMonitor->isVisible())
                PCameraMonitor->show();
        });
        break;
    case 8:
        //加载天气预报
        PTianqiYubao = new TianqiYubao(this);
        ui->frmWeather->addWidget(PTianqiYubao);
        ui->frmWeather->setCurrentWidget(PTianqiYubao);
        break;
    default:
        break;
    }
    int mIndex = index + 1;
    if(mIndex > 8)
        return;
    QMetaObject::invokeMethod(this, "fnChainLoading",
        Qt::QueuedConnection,
        Q_ARG(int, mIndex));
}

/**
 * 打开设置界面
 * @brief Monitor::onOpenNavigation
 */
void Monitor::onOpenNavigation(){
    if(PGNavigation != nullptr && PGNavigation->isVisible()){
        PGNavigation->close();
        return;
    }
    if(PGNavigation == nullptr){
        PGNavigation = new Navigation(this);
        int posx = this->width() - PGNavigation->width();
        PGNavigation->move(posx, 79);
    }
    PGNavigation->show();
}

/**
 * @brief Monitor::fnShowLoginWidget
 * 打开登录界面
 */
void Monitor::fnShowLoginWidget(){
    if(PGUsrLogin == nullptr){
        PGUsrLogin = new UsrLogin(this);
        connect(PGUsrLogin, &UsrLogin::callLoginSucceeded, this, [=](){
            this->fnLoginSucceeded();
        });
    }
    if(PGUsrLogin && !PGUsrLogin->isVisible())
        PGUsrLogin->show();
}

/**
 * 打开用户帐户和设置界面
 * @brief Monitor::fnOpenPage
 */
void Monitor::fnOpenPage(QString tye){
    if(tye == "UserLogin"){
        // 用户登录
        fnShowLoginWidget();
        return;
    }
    if(tye == "UsrInfo"){
        // 用户帐户
        if(PGUsrInfo == nullptr)
            PGUsrInfo = new UsrInfo(this);
        if(PGUsrInfo && !PGUsrInfo->isVisible())
            PGUsrInfo->show();
        return;
    }
    if(tye == "BindDevice"){
        // 绑定新设备
        if(PGUsrBind == nullptr)
            PGUsrBind = new UsrBind(this);
        if(PGUsrBind && !PGUsrBind->isVisible())
            PGUsrBind->show();
        return;
    }
    if(tye == "SystemSetup"){
        // 系统设置
        if(PGUsrSettings == nullptr)
            PGUsrSettings = new UsrSettings(this);
        if(PGUsrSettings && !PGUsrSettings->isVisible())
            PGUsrSettings->show();
        return;
    }
    if(tye == "CustomerService"){
        // AI 赋能
        return;
    }
    if(tye == "CheckVersion"){
        // 检查升级
        QMetaObject::invokeMethod(PMonitorWork, "fnCheckNewVersion",
            Qt::QueuedConnection,
            Q_ARG(bool, false));
        return;
    }
    if(tye == "linkSwitchUser" || tye == "linkLogout"){
        // 切换用户/用户登出
        QStringList keys = Global::usrLoggedInfo.keys();
        for (const QString &key : keys)
            Global::usrLoggedInfo.remove(key);
        QStringList fiConfigValue;
        fiConfigValue.push_back("/General/usrLoggedInfo");
        fiConfigValue.push_back(QString());
        Global::fnWriteConfigSingle(fiConfigValue);
        fiConfigValue.clear();
        if(tye == "linkSwitchUser"){
            // 切换用户，重启系统
            QTimer::singleShot(100, this, [=]() {
                QString program = qApp->arguments().first();
                QStringList args = qApp->arguments().mid(1);
                qApp->quit();
                QProcess::startDetached(program, args);
            });
        }else{
            // 用户登出，关闭系统
            Global::fnSaveOperation("用户主动退出登录");
            this->fnShowMessages({"5", "已退出登录，系统即将关闭！"});
            QTimer::singleShot(2000, this, [=](){ ui->BtnMainClose->click(); });
        }
        return;
    }
    // 新用户注册
    if(tye == "linkUserReg"){
        if(PGUsrRegister == nullptr)
            PGUsrRegister = new UsrRegister(this);
        if(PGUsrRegister && !PGUsrRegister->isVisible())
            PGUsrRegister->show();
        return;
    }
    // 找回密码
    if(tye == "linkForgotPasswd"){
        if(PGUsrFindpwd == nullptr)
            PGUsrFindpwd = new UsrFindpwd(this);
        if(PGUsrFindpwd && !PGUsrFindpwd->isVisible())
            PGUsrFindpwd->show();
        return;
    }
    // 天气预报设置
    if(tye == "WeatherSetup"){
        if(Global::usrLoggedInfo.isEmpty()){
            this->fnOpenPage("UserLogin");
            return;
        }
        if(!Global::lstAuthority.contains(Global::strAuthority)){
            this->fnShowMessages({"4", "用户权限不足，请核实！"});
            return;
        }
        if(PGWeatherSetup == nullptr){
            PGWeatherSetup = new WeatherSetup(this);
            connect(PGWeatherSetup, &WeatherSetup::CallUpdateCompleted,
                    PTianqiYubao, &TianqiYubao::fnCreateWeather);
        }
        PGWeatherSetup->show();
        QTimer::singleShot(20, this, [=]{
            if(PGWeatherSetup->isHidden())
                PGWeatherSetup->show();
        });
        return;
    }
    // 搜索设备弹窗
    if(tye == "SearchDevice"){
        if(Global::usrLoggedInfo.isEmpty()){
            this->fnOpenPage("UserLogin");
            return;
        }
        if(PGSearchDevice == nullptr){
            PGSearchDevice = new SearchDevice(this);
            connect(PGSearchDevice, &SearchDevice::CallDeviceKeyword,
                    PDevicesList, &DevicesList::fnGetDeviesList);
        }
        PGSearchDevice->show();
        QTimer::singleShot(20, this, [=]{
            if(PGSearchDevice->isHidden())
                PGSearchDevice->show();
        });
        ui->BtnMainMax->click();
    }
    // 区域分布统设置
    if(tye == "DeviceStatiSetup"){
        if(Global::usrLoggedInfo.isEmpty()){
            this->fnOpenPage("UserLogin");
            return;
        }
        if(!Global::lstAuthority.contains(Global::strAuthority)){
            this->fnShowMessages({"4", "用户权限不足，请核实！"});
            return;
        }
        if(PDeviceStatiSetup == nullptr){
            PDeviceStatiSetup = new DeviceStatiSetup(this);
            int top = ui->WidHeader->height() + ui->frmStatistics->height() + 62;
            int left = this->width() - ui->frmRealdata->width() - PDeviceStatiSetup->width() - 15;
            PDeviceStatiSetup->move(left, top);
        }
        PDeviceStatiSetup->show();
        QTimer::singleShot(20, this, [=]{
            if(PDeviceStatiSetup->isHidden())
                PDeviceStatiSetup->show();
        });
        return;
    }
    // 黑名单管理
    if(tye == "BlackList"){
        if(Global::strAuthority != "9"){
            this->fnShowMessages({"4", "用户权限不足，请核实！"});
            return;
        }
        if(PBlackList == nullptr)
            PBlackList = new BlackList(this);
        if(PBlackList && !PBlackList->isVisible())
            PBlackList->show();
        return;
    }
}

/**
 * 响应内页信号
 * @brief Monitor::fnInsidePageAction
 * @param param
 */
void Monitor::fnInsidePageAction(QStringList param){
    QString firstAction = param.first();
    if(firstAction == "OpenInsidePage"){
        if(param.size() < 2)
            return;
        this->fnOpenPage(param.at(1));
        return;
    }
    // 设置平台名称
    if(firstAction == "PlatformNameChanged"){
        QString PlatformName = Global::PlatformName;
        if(!Global::usrSettingsInfo.isEmpty()){
            QString apptitle = Global::usrSettingsInfo.value("apptitle").toString();
            if(!apptitle.isEmpty()){
                PlatformName = apptitle;
            }
        }
        if(ui->labPlatformName->text() != PlatformName)
            ui->labPlatformName->setText(PlatformName);
        return;
    }
    // 显示对话框
    if(firstAction == "ShowMessages"){
        param.removeFirst();
        if(param.first() == "UsrSettingsInfoChanged"){
            //设置用户信息完成
            param.removeFirst();
            this->fnInsidePageAction(QStringList("PlatformNameChanged"));
            if(PDevCarousel){
                int animationDuration = Global::usrSettingsInfo.value("deviceinterval").toString().toInt();
                if(animationDuration < 10)
                    animationDuration = 10;
                PDevCarousel->animationDuration = animationDuration * 1000;
            }
            if(PTopStatistics)
                PTopStatistics->fnGetStatisticsData();
        }
        this->fnShowMessages(param);
        return;
    }
    // MQTT信息发送返馈
    if(firstAction == "MqttPublished"){
        if(param.size() > 2 && param.last() == Global::idMqttMessage){
            QString msgtye = param.at(1) == "Failure" ? "3" : "1";
            this->fnShowMessages({msgtye, param.at(2)});
            return;
        }
    }
    // 窗口还原
    if(firstAction == "WindowRestore"){
        ui->BtnMainMax->click();
        return;
    }
    // 订阅新设备 / 打开设备详情
    if(firstAction == "OpenDeviceDetail"){
        if(PV20Main && PV20Main->isVisible())
            PV20Main->close();
        if(PV15Main && PV15Main->isVisible())
            PV15Main->close();
        if(PV10Main && PV10Main->isVisible())
            PV10Main->close();

        if(Global::usrLoggedInfo.isEmpty() || !Global::usrLoggedInfo.contains("uid")){
            this->fnShowMessages({"4", "用户未登录或登录超时！"});
            return;
        }

        // 订阅实时数据
        QMetaObject::invokeMethod(PMonitorWork, "fnMqttSubscribe");

        // 判断是否需要输入密码，打开设备详情
        Global::CurrDevNumberPasswd = "";
        QMetaObject::invokeMethod(PMonitorWork,
                        "fnHasOptionPasswd",
                        Qt::DirectConnection);
        return;
    }
}

/**
 * @brief Monitor::fnOpenDeviceDetail
 * 打开设备详情
 */
void Monitor::fnOpenDeviceDetail(float version){
    // QElapsedTimer timer;
    // timer.start();
    if(version < 1){
        this->fnShowMessages({"4", "未能获得该设备的版本信息\n请重试或联系管理员"});
        return;
    }

    QWidget *opWidget = nullptr;
    if(version >= 3){

    }else if(version < 3 && version >= 2){
        if(PV20Main == nullptr)
            PV20Main = new V20Main(this);
        opWidget = PV20Main;
    }else if(version < 2 && version >= 1.5){
        if(PV15Main == nullptr)
            PV15Main = new V15Main(this);
        opWidget = PV15Main;
    }else{
        if(PV10Main == nullptr)
            PV10Main = new V10Main(this);
        opWidget = PV10Main;
    }

    if(opWidget == nullptr){
        this->fnShowMessages({"3", "没有匹配到与版本对应的操作模块。\n请重试或联系管理员！"});
        return;
    }
    opWidget->show();

    // qint64 elapsedMs = timer.elapsed();  // 获取耗时（毫秒）
    // qDebug() << "fnOpenDeviceDetail执行时间:" << elapsedMs << "ms";
}

/**
 * 日期和时间
 * */
void Monitor::fnUpdateTime(){
    static QString lastTime;
    QDateTime localTime = QDateTime::currentDateTime();
    QString currTime = localTime.toString("hh:mm:ss");
    // clazy:exclude=qdatetime-utc
    if (currTime != lastTime) {
        lastTime = currTime;
        ui->labCurrTime->setText(localTime.toString("hh:mm:ss"));
        ui->labCurrDate->setText(localTime.toString("yyyy 年 MM 月 dd 日"));
        QString week = QLocale(QLocale::Chinese, QLocale::China).toString(localTime, "dddd");
        ui->labCurrWeek->setText(week);
    }
}

/**
 * 显示对话框
 * @brief Monitor::fnShowMessages
 * @param param{type, message}
 */
void Monitor::fnShowMessages(QStringList param){
    if(param.at(0).toInt() == 0){
        if(PGDialog && PGDialog->isVisible())
            PGDialog->setVisible(false);
        return;
    }
    if(PGDialog != nullptr){
        disconnect(PGDialog, nullptr, nullptr, nullptr);
        PGDialog->deleteLater();
        PGDialog = nullptr;
    }
    PGDialog = new Dialog(param, this);
    PGDialog->show();
    QTimer::singleShot(20, this, [=]{
        PGDialog->activateWindow();
        PGDialog->raise();
        PGDialog->setFocus();
    });
}

/**
 * 显示报警图标
 * 清理不存在的设备
 * */
void Monitor::fnShowFaultAlarm(QMap<QString, QVariant> devStateResult){
    if(PCameraMonitor && PCameraMonitor->isVisible())
        return;
    if(PV10Main && PV10Main->isVisible())
        return;
    if(PV15Main && PV15Main->isVisible())
        return;
    if(PV20Main && PV20Main->isVisible())
        return;

    // 清理不存在的设备
    QStringList lstLostNumber = devStateResult.value("lstLostNumber").toStringList();
    if(lstLostNumber.size() > 0 && Global::strAuthority == "9"){
        QMetaObject::invokeMethod(PMonitorWork, "fnCleanInvalidDevice",
                  Qt::QueuedConnection,
                  Q_ARG(QStringList, lstLostNumber));
    }
    QString alertLevel = Global::usrSettingsInfo.value("alertlevel").toString();
    if(alertLevel.isEmpty())
        return;
    if(alertLevel.toInt() == 2){
        if(devStateResult.value("fault").toInt() == 0)
            return;
    }
    if(alertLevel.toInt() == 1){
        if(devStateResult.value("alarm").toInt() == 0
            && devStateResult.value("fault").toInt() == 0)
            return;
    }
    if(PDevFaultAlarm == nullptr){
        PDevFaultAlarm = new DevFaultAlarm(this);
        int x = ui->MainWidget2->width() + ui->frmMap->width() - PDevFaultAlarm->width() + 6,
            y = ui->frmMap->height() + ui->WidHeader->height() + ui->frmStatistics->height()
                - PDevFaultAlarm->height() + 12;
        PDevFaultAlarm->move(x,y);
        connect(PDevFaultAlarm, &DevFaultAlarm::CallOpenAlarmList, this, &Monitor::fnOpenAlarmList);
    }
    if(PDevFaultAlarm){
        // 如果点击关闭，且结果相同，则不再显示
        if(alertLevel.toInt() == 1){
            if(PDevFaultAlarm->isClosed){
                if(devStateResult.value("lstFault").toStringList() == PDevFaultAlarm->lstFault
                    && devStateResult.value("lstAlarm").toStringList() == PDevFaultAlarm->lstAlarm)
                    return;
            }
        }
        if(alertLevel.toInt() == 2){
            if(PDevFaultAlarm->isClosed){
                if(devStateResult.value("lstFault").toStringList() == PDevFaultAlarm->lstFault)
                    return;
            }
        }
        PDevFaultAlarm->lstAlarm.clear();
        PDevFaultAlarm->lstAlarm = devStateResult.value("lstAlarm").toStringList();
        PDevFaultAlarm->lstFault.clear();
        PDevFaultAlarm->lstFault = devStateResult.value("lstFault").toStringList();
        if(!PDevFaultAlarm->isVisible())
            PDevFaultAlarm->show();
    }
}
/**
 * 打开报警列表
 * */
void Monitor::fnOpenAlarmList(QStringList lstAlarm, QStringList lstFault){
    if(PDevFaultList==nullptr){
        PDevFaultList = new DevFaultList(this);
        int x = ui->MainWidget2->width() + ui->frmMap->width() - PDevFaultList->width() + 6,
            y = ui->frmMap->height() + ui->WidHeader->height() + ui->frmStatistics->height()
                - PDevFaultList->height() + 12;
        PDevFaultList->move(x,y);
    }
    if(PDevFaultList){
        PDevFaultList->lstAlarm.clear();
        PDevFaultList->lstAlarm = lstAlarm;
        PDevFaultList->lstFault.clear();
        PDevFaultList->lstFault = lstFault;
        if(!PDevFaultList->isVisible())
            PDevFaultList->show();
    }
}

/**
 * @brief Monitor::fnCheckNewVersion
 * 检查新版本返回，登录
 */
void Monitor::fnCheckNewVersion(bool Finished){
    if(Finished)
        fnShowLoginWidget();
}

void Monitor::fnMonitorWorkInfo(QStringList info){
    if(info.first() == "showErrorMessage"){
        if(info.size() < 3)
            return;
        this->fnShowMessages({info.at(1), info.at(2)});
        return;
    }
    if(info.first() == "checkHasOptionPasswd"){
        // 打开设备详情时，判断是否需要输入密码（返回）
        if(info.size() < 2)
            return;
        bool hasOptionPasswd = info.last() == "true"?true:false;
        if(!hasOptionPasswd){
            QMetaObject::invokeMethod(PMonitorWork,
                                      "fnReturnVersion",
                                      Qt::QueuedConnection);
            return;
        }
        if(!PPassWd){
            PPassWd = new PassWd(Global::CurrDevNumber,this);
            connect(PPassWd, &PassWd::CallPasswordVerification, this, [=](QString Ops){
                if(Ops == "OptionsCancel"){
                    // 自行退出
                    QMetaObject::invokeMethod(PMonitorWork, "fnMqttUnsubscribed");
                    return;
                }else{
                    // 获取版本号打开相应的详情页
                    QMetaObject::invokeMethod(PMonitorWork,
                                              "fnReturnVersion",
                                              Qt::QueuedConnection);
                };
            });
            PPassWd->setWindowFlags(Qt::WindowStaysOnTopHint);
            QRect rect = this->geometry();
            int x = (rect.width() - PPassWd->width()) / 2;
            int y = (rect.height() - PPassWd->height()) / 2;
            PPassWd->move(x, y);
        }else PPassWd->reset(Global::CurrDevNumber);
        if(PPassWd)
            PPassWd->show();
        return;
    }
}

/**
 * 界面最大化最小化
 * @brief Monitor::onWindowGeometry
 */
void Monitor::onWindowGeometry(){
    QPushButton *tiButton = qobject_cast<QPushButton *>(sender());
    QString objName = tiButton->objectName();
    if(objName == "BtnMainMin"){
        this->showMinimized();
    }
    if(objName == "BtnMainMax"){
        if(this->isMaximized()){
            this->showNormal();
            return;
        }
        this->showMaximized();
    }
    if(objName == "BtnMainClose"){
        qApp->closeAllWindows();
    }
}

/****************
 * 窗体拖动(LOGO区域)
 *******************/
void Monitor::mouseMoveEvent(QMouseEvent *e){
    if(mousePressed && mousePoint.y() < 90){
        if (e->buttons() | Qt::LeftButton)
            this->move(e->globalPos() - mousePoint);
        e->accept();
    }
}

void Monitor::mousePressEvent(QMouseEvent *e){
    if (e->button() == Qt::LeftButton) {
        mousePressed = true;
        mousePoint = e->globalPos() - this->pos();
        e->accept();
    }
}

void Monitor::mouseReleaseEvent(QMouseEvent *){
    mousePressed = false;
    if(this->pos().x() < 90 || this->pos().y() < 90)
        this->move(0,0);
}

void Monitor::showEvent(QShowEvent*){

}

